import server from 'axios'
import md5 from '@/utils/md5'
import auth from '@/utils/auth';
import config from '@/config/config'


export default {
    get:get,
    post:post,
    upload:upload,
};


async function get(options) {
    if (!options) {options = {method:"get"}}
    options.method = "get"

    return new Promise((resolve, reject) => {
        _request(options, resolve, reject)
    })
}

async function post(options) {
    if (!options) {options = {method:"post"}}
    options.method = "post"

    return new Promise((resolve, reject) => {
        _request(options, resolve, reject)
    })
}

/** 封装接口请求处理
 必要参数：url
 page：当前页面对象
 data: 请求参数
 header: 头
 method： 默认GET
 */
const _request = async function (options, resolve, reject) {
    if (!options || !options.url) { if (reject) reject({code:1000, msg:"缺少参数"}) }

    if (!options.data) {options.data = {}}
    if (!options.header) {options.header = {}}
    options.method = !options.method ? 'get' : options.method.toLowerCase();

    options.header["Content-Type"] = "application/json;charset=UTF-8"
    options.header["Authorization"] = auth.getToken()

    if (options.needSign) {
        let timestamp = Date.parse(new Date()) / 1000
        let s = 'bc99u%^yr3i' + timestamp
        if (options.header.id) { s += options.header.id }
        s = md5.hex_md5(s)
        options.header["timestamp"] = timestamp
        options.header["sign"] = s
    }

    if (options.method === "post") {
        server.post(options.url, options.data, {
            baseURL: options.url.indexOf("http") === 0 ? '' : config.baseApi,
            headers: options.header,
        }).then((res) => {
            _requestDoneBlock(res, resolve, reject);
        }, res => {
            _requestDoneBlock(res, resolve, reject);
        });
    } else {
        server.request({
            baseURL: options.url.indexOf("http") === 0 ? '' : config.baseApi,
            url: options.url,
            method: options.method,
            params: options.data, headers: options.header,
        }).then((res) => {
            _requestDoneBlock(res, resolve, reject);
        }, res => {
            _requestDoneBlock(res, resolve, reject);
        });
    }
};

async function upload(options) {
    return new Promise((resolve, reject) => {
        if (!options || !options.url) { if(reject) reject({code:2000, msg:"缺少必要参数"}); return}
        if (!options.data) { reject({code:2000, msg:"缺少必要参数"}); return}
        if (!options.url) { options.url = "tio/upload.file" }

        //请求头
        let headers = options.header || {}
        headers["Content-Type"] = "multipart/form-data"
        headers["Authorization"] = auth.getToken()

        //签名
        let signInfo = _paramsWithSign(options.data)
        headers.timestamp = signInfo.timestamp
        headers.sign = signInfo.sign

        server.post(options.url, options.data, {
            baseURL: options.url.indexOf("http") === 0 ? '' : config.baseApi,
            headers: headers,
        }).then((res) => {
            _requestDoneBlock(res, resolve, reject);
        }, res => {
            _requestDoneBlock(res, resolve, reject);
        });
    })
}

const _jumpLogin = function() {
    auth.setToken(null)
    if (!(/\/(login|register)/).test(location.href)) location.reload()
}

const _requestDoneBlock = function (res, resolve, reject) {
    if (res && res.status === 200) {
        if (!res || !res.data) {
            reject({code:1000, msg:"出错啦~"});
        }

        let data = res.data;
        if (res.data.code === 0) {
            resolve(data);
        } else if (data.code === 3100) {
            //打开登录页面
            _jumpLogin()
        } else {
            reject({code:1000, msg:data.msg || '出错啦~'});
        }
    } else {
        let data = {code:1000};
        if (res && res.response && res.response.data) {
            data = res.response.data;
        }

        if (data.code === 3100) {
            //打开登录页面
            _jumpLogin()
        } else {
            reject({code:1000, msg:data.msg || '出错啦~'});
        }
    }
};

const _paramsWithSign = function (obj) {
    if (!obj) {obj = {}}

    let timestamp = Date.parse(new Date()) / 1000
    let s = 'bc99u%^yr3i' + timestamp
    if (obj.id) { s += obj.id }
    s = md5.hex_md5(s)
    return {timestamp:timestamp, sign:s};
}
